import StepNumber from "../carousel/swiper/StepNumber.js";
import LStorage from './localtion.js';
import Component from "../carousel/swiper/Component.js"
new LStorage()
class Buycar extends Component {
    tbody;
    all;
    sums;
    goodsbody;
    b;
    hoppingList = [];
    goodsingList = [];
    numstep;
    parents;
    del;
    arr=[];
    shopnums;
    counts;
    delselect;
    payout;
    constructor() {
        super();
        this.tbody = document.querySelector(".goodsbody");
        this.all = document.querySelectorAll(".selectall");
        this.sums = document.querySelector(".sums");
        this.parents = document.querySelector(".goodsparent")
        this.goodsbody = document.querySelector(".goodsbody");
        this.counts=document.querySelector('.n-counts');
        this.shopnums=document.querySelector('.shopnums')
        this.payout=document.querySelector(".payout");
        this.payout.addEventListener('click',e=>this.payoutHandle(e))
        this.arrcarHandler(); 
        this.all.forEach((item,index)=>{
            item.addEventListener("click", e => this.selectHandler(e,index));   
        })
        
    }
    payoutHandle(e){
        location.href='./nowbuy.html'
    }
   delselectGoods(e,selects,s){
        selects.forEach((item,index)=>{
            if(item.checked){
                
                this.delHanlder(index,s)
            }
        })
    }
    selectHandler(e,i){
        i===0?this.all[1].checked= e.target.checked:this.all[0].checked= e.target.checked;
        this.selects.forEach(item=>{
            item.checked=e.target.checked
        });
        if(this.all[0].checked){
            var num=0;
            var c=0
            var s= e.target===this.all[0]? e.target.parentElement.parentElement. nextElementSibling.children:e.target.parentElement.parentElement.previousElementSibling.children;
             s=Array.from(s)
            s.forEach(item=>{
             num+=Number(item.children[6].children[1].value) ;
             c+=Number(item.children[4].innerHTML);
         })
         this.shopnums.textContent=`选中的${num}个商品`;
         this.counts.innerHTML=`￥${c}`
        }else if(!this.all[0].checked){
            this.shopnums.textContent=`选中的0个商品`
            this.counts.innerHTML=`￥0`
        }
   }
   selectItem(){
        this.selects=Array.from( this.selects)
        this.selects.forEach(item=>{
            this.all.forEach(t=>{
                t.checked=item.checked
            })
            item.addEventListener('click',e=>this.selectItemHandler(e))
        })
   }
   selectItemHandler(e){      
    this.selects=Array.from( this.selects);
      var s= this.selects.every(function(item){  
         return  item.checked===true
       })
       this.all.forEach(t=>{
        t.checked= s===true? true:false
       })
       var pos=this.selects.indexOf(e.target)
     if(!this.arr.includes(pos)){
         this.arr.push(pos)
     } else{
         var index=this.arr.indexOf(pos);
         this.arr.splice(index,1)
        };
      this.changeLastText(this.arr,e.target,pos)
     
   }
   changeLastText(arr,b,pos){
       var v=0;
       var c=0
       arr.length=0
       this.selects.forEach(item=>{
        if(item.checked){    
          var s= this.selects.indexOf(item);          
          arr.push(s)
        }
    })
      arr.forEach((item,index)=>{    
         v+= Number( this.selects[item].parentElement.children[6].children[1].value);  
         c+= Number( this.selects[item].parentElement.children[4].innerHTML); 
        });
        this.shopnums.textContent=`选中的${v}个商品`;
        this.counts.innerHTML=`￥${c}`
   }
    async appendGoods(sn) {
       if(window.location.href.split("?")[1]){
        var arr = window.location.href.split("?")[1].split("/");
        arr[2] = decodeURI(arr[2])
        var temp = arr[1];
        arr[1] = arr[3];
        arr[3] = temp
        arr.unshift(sn)
        var data = await fetch('http://localhost:4020/setCar', {
            method: 'post',
            body: JSON.stringify(arr)
        });
        data = await data.json()
        data = data.result;
    }}
    async allcar(sn) {
        var data = await fetch('http://localhost:4020/searchUser', {
            method: 'post',
            body: JSON.stringify(sn)
        });
        data = await data.json()
        data = data.result;
        var s = await this.imgLoad(data)
        this.randerbody(data,s)
         this.selects=document.querySelectorAll('.select');
        this.del = document.querySelectorAll(".n-done");
        this.selectItem()
        this.delselect=document.querySelector('.delselect');
        this.delselect.addEventListener('click',e=>this.delselectGoods(e,this.selects,s))
        this.del.forEach((item) => {
            item.addEventListener('click', e => this.delHanlder(e, s))
        }, this)
    }
    async delHanlder(e, s) {
        var pos;
        
        if(typeof e==='number'){
           pos=e;
          
        }else{
            
         pos = Array.from(this.del).indexOf(e.target);
         
        }
        var data = await fetch('http://localhost:4020/deldata', {
            method: 'post',
            body: JSON.stringify(s[pos].productSid)
        });
        data = await data.json()
        if (data) {
           
            this.parents.children[pos].style.display = 'none'
        }
    }
    async randerbody(data, s) {
        for (var i = 0; i < data.length; i++) {
            var ele = document.createElement('div');
            ele.className = 'goodsbody';
            var p = Number(s[i].minSellingPrice) * Number(data[i].num);
            ele.innerHTML = `
            <input type="checkbox" name="select-all" class="select">     
            <div class="t-goods n-goods ">
            <img src="${s[i].proPictDir}">
            <p>${s[i].productName}</p>
            <div class="len">
            <span>${data[i].color}</span>
            <span>${data[i].size}</span>
            </div>
            </div>
            <div class="t-price n-price">${s[i].minSellingPrice}</div>
            <div class="t-count n-num "></div>
            <div class="t-sum n-sum">${p}</div>
            <div class="t-done n-done">删除</div      
            `
            this.b = new StepNumber();      
            this.b.addEventListener(StepNumber.STEP_CHANGE_EVENT, e => this.myLister(e, data, s));
            this.b.step = Number(data[i].num);
            this.b.input.value = Number(this.b.step)
            this.parents.appendChild(ele)
            ele.appendChild( this.b.elem)
        }
    }
    arrcarHandler() {
        var s = localStorage.getItem('user');
        if (!s) {
            alert('您还没有登录，请登录')
            location.href = './login.html'
        }
       this.appendGoods(s)
        this.allcar(s)
    }
    async imgLoad(datas) {
        var arry = []
        for (var i = 0; i < datas.length; i++) {
            var data = await fetch('http://localhost:4020/getdata', {
                method: 'post',
                body: JSON.stringify(datas[i].productSid)
            });
            data = await data.json()
            data = data.result[0]
            data.skuList = JSON.parse(data.skuList);
            arry.push(data);
        }
        var s = localStorage.getItem('user');
        return arry
    }
    myLister(e, data, arr) {
        var divs = document.querySelectorAll(".numstep");
        var pos = Array.from(divs).indexOf(e.target.elem);
        // if(e.target.elem.parentElement.firstElementChild.checked){
            
        // }
        this.getCar(data[pos], arr, pos);
    }

    async getCar(datas, arrs, pos) {
        var arr = Array.from(arguments)
        arr = arr[0]
        var data = await fetch('http://localhost:4020/setCar', {
            method: 'post',
            body: JSON.stringify(arr)
        });
        data = await data.json()
        data = data.result;

        if (!data) {
            var index = document.querySelectorAll(".numstep")
            var Input = index[pos].querySelector('input');
            var text = document.querySelectorAll(".n-sum");
            arr.num = Input.value
            var p = Number(arrs[pos].minSellingPrice) * Number(arr.num);
            text[pos].innerHTML = "";
            text[pos].innerHTML = p;
            var lists = await fetch('http://localhost:4020/getCar', {
                method: 'post',
                body: JSON.stringify(arr)
            });
            lists = await lists.json();
            lists = lists.result
            if (lists === true) {
                var da = await fetch('http://localhost:4020/upCar', {
                    method: 'post',
                    body: null

                });
                da = await da.json();
                da = da.result[0].num;
            }
        };
    }
    emsclick(e) {
        localStorage.clear();
        this.username.style.display = 'none';
        this.lis.forEach((item) => {
            item.style.display = 'block'
        })
    }
}
new Buycar()